package middleware

import (
	"errors"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

func MaxBytesMiddleware(limit int64) rest.Middleware {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			r.Body = http.MaxBytesReader(w, r.Body, limit)
			err := r.ParseMultipartForm(limit)
			if err != nil {
				httpx.Error(w, errors.New(http.StatusText(http.StatusRequestEntityTooLarge)))
				return
			}
			next(w, r)
		}
	}
}
